package com.real.operationalcontrols;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import androidx.multidex.MultiDex;

import com.assionhonty.lib.assninegridview.AssNineGridView;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.king.base.baseurlmanager.BaseUrlManager;
import com.king.base.baseurlmanager.IBaseUrlManager;
import com.king.base.baseurlmanager.bean.UrlInfo;
import com.mob.MobSDK;
import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCustomMessage;
import com.mob.pushsdk.MobPushNotifyMessage;
import com.mob.pushsdk.MobPushReceiver;
import com.previewlibrary.ZoomMediaLoader;
import com.simple.spiderman.SpiderMan;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import me.jessyan.autosize.AutoSizeConfig;
import okhttp3.OkHttpClient;
import rxhttp.RxHttpPlugins;
import rxhttp.wrapper.cahce.CacheMode;
import rxhttp.wrapper.cookie.CookieStore;
import rxhttp.wrapper.param.RxHttp;
import rxhttp.wrapper.ssl.SSLSocketFactoryImpl;
import rxhttp.wrapper.ssl.X509TrustManagerImpl;

public class App extends Application {
    public static Context context;
    public static IBaseUrlManager mBaseUrlManager;
    private String[] mUrls = {
            "http://222.223.112.252:11777/",
            "http://183.196.178.13:11777/",
            "http://111.61.64.41:11777/",
            "http://222.222.220.218:11777/",
            "http://183.196.173.163:11777/",
            "http://111.61.249.50:11999/"
    };
    private String[] mUrlsName = {
            "清河", "南宫", "藁城", "晋州", "宁晋", "海港"
    };

    @Override
    public void onCreate() {
        super.onCreate();
        //闪退报告收集
        SpiderMan.init(this);
        context = this;
        Utils.init(this);
        //开启对片段的支持
        AutoSizeConfig.getInstance().setCustomFragment(true);
        AssNineGridView.setImageLoader(new GlideImageLoader());
        ZoomMediaLoader.getInstance().init(new com.real.operationalcontrols.工具包.GlideImageLoader());
        initBaseUrlManager();
        initPush();
        initRxhttp();
        LogConfiguration config = new LogConfiguration.Builder()
                .tag("gaogao")
                .logLevel(LogLevel.ALL)
                .b()
                .build();
        XLog.init(config);
        //升级更新
        initUpdate();
    }

    private void initUpdate() {
        Context context = getApplicationContext();
// 获取当前包名
        String packageName = context.getPackageName();
// 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
// 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
// 初始化Bugly
        Bugly.init(getApplicationContext(), "9e52ce85bb", false, strategy);
    }

    private void initPush() {
        MobSDK.submitPolicyGrantResult(true, null);
        MobSDK.init(this);
        MobPush.addPushReceiver(new MobPushReceiver() {
            @Override
            public void onCustomMessageReceive(Context context,
                                               MobPushCustomMessage mobPushCustomMessage) {
                Log.i("MobPushLogger", "接收自定义消息");
            }

            @Override
            public void onNotifyMessageReceive(Context context,
                                               MobPushNotifyMessage mobPushNotifyMessage) {
                Log.i("MobPushLogger", "接收通知消息");
            }

            @Override
            public void onNotifyMessageOpenedReceive(Context context,
                                                     MobPushNotifyMessage mobPushNotifyMessage) {
                Log.i("MobPushLogger", "接收通知消息被点击事件");
            }

            @Override
            public void onTagsCallback(Context context, String[] strings, int i, int i1) {
                Log.i("MobPushLogger", "接收tags的增改删查操作");
            }

            @Override
            public void onAliasCallback(Context context, String s, int i, int i1) {
                Log.i("MobPushLogger", "接收alias的增改删查操作");
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
        {
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    //防止APP字体随系统变化
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1.0f) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initRxhttp() {
        X509TrustManager trustAllCert = new X509TrustManagerImpl();
        SSLSocketFactory sslSocketFactory = new SSLSocketFactoryImpl(trustAllCert);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //设置缓存目录为：Android/data/{app包名目录}/cache/RxHttpCache
        File cacheDir = new File(getExternalCacheDir(), "RxHttpCache");
        //设置最大缓存为10M，缓存有效时长为60秒
        RxHttpPlugins.setCache(cacheDir, 10 * 1024 * 1024,
                CacheMode.ONLY_NETWORK, 60 * 1000);
        builder.cookieJar(new CookieStore());
        //全局的读取超时时间
        builder.readTimeout(10000, TimeUnit.MILLISECONDS);
        //全局的写入超时时间
        builder.writeTimeout(10000, TimeUnit.MILLISECONDS);
        //全局的连接超时时间
        builder.connectTimeout(10000, TimeUnit.MILLISECONDS);
        //设置地址拦截器
        builder.sslSocketFactory(sslSocketFactory, trustAllCert);//添加信任证书
        builder.hostnameVerifier((hostname, session) -> true); //忽略host验证
        RxHttp.init(builder.build());
    }

    public static Context getContext() {
        return context;
    }

    /**
     * Picasso 加载
     */
    private class GlideImageLoader implements AssNineGridView.ImageLoader {

        @Override
        public void onDisplayImage(Context context, ImageView imageView, String url) {
            RequestOptions option = new RequestOptions();
            option.error(R.drawable.ic_default_image);
            option.placeholder(R.drawable.ic_default_image);
            Glide.with(context).load(url).apply(option).into(imageView);
        }

        @Override
        public Bitmap getCacheImage(String url) {
            return null;
        }
    }

    /**
     * 初始化{@link #mBaseUrlManager}
     */
    private void initBaseUrlManager() {
        //初始化BaseUrlManager
        mBaseUrlManager = new BaseUrlManager(this);
        List<UrlInfo> list = new ArrayList<>();
        for (int i = 0; i < mUrls.length; i++) {
            list.add(new UrlInfo(mUrls[i], mUrlsName[i]));
        }
        mBaseUrlManager.addUrlInfo(list);
        //设置baseUrl
        //mBaseUrlManager.setUrlInfo(list.get(0));
    }

    /**
     * 获取baseUrl
     *
     * @return {@link #mBaseUrlManager#getBaseUrl()}
     */
    public static String getBaseUrl() {
        return mBaseUrlManager.getBaseUrl();
    }

    /**
     * 获取 {@link IBaseUrlManager}
     *
     * @return {@link #mBaseUrlManager}
     */
    public static IBaseUrlManager getBaseUrlManager() {
        return mBaseUrlManager;
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }
}
